import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const username = ref('')
  const avatar = ref('')
  const roles = ref([])
  const permissions = ref([])

  // 登录
  const login = (userInfo) => {
    // 模拟登录，实际项目中会调用API
    const { username: name, password } = userInfo
    // 假设只要密码长度大于5就登录成功
    if (password.length > 5) {
      token.value = `token-${Date.now()}`
      username.value = name
      avatar.value = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      roles.value = ['admin']
      permissions.value = ['*:*:*']
      // 保存登录状态到本地存储
      localStorage.setItem('token', token.value)
      return Promise.resolve()
    } else {
      return Promise.reject('密码至少需要6位')
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    username.value = ''
    avatar.value = ''
    roles.value = []
    permissions.value = []
    // 清除本地存储的登录状态
    localStorage.removeItem('token')
    return Promise.resolve()
  }

  return {
    token,
    username,
    avatar,
    roles,
    permissions,
    login,
    logout
  }
}, {
  persist: {
    key: 'vue3-demo-user',
    storage: localStorage
  }
}) 